package com.example.controller;

import com.example.elasticsearch.data.MyDocument;
import com.example.service.MyDocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/my/document")
public class MyDocumentController {

    @Autowired
    private MyDocumentService documentService;

    // 查询所有文档
    @GetMapping("/all")
    public Page<MyDocument> getAllDocuments(
            @RequestParam(value = "page", defaultValue = "0") int page,
            @RequestParam(value = "size", defaultValue = "10") int size) {
        return documentService.findAll(PageRequest.of(page, size));
    }

    // 根据ID查询文档
    @GetMapping("/{id}")
    public Optional<MyDocument> getDocumentById(@PathVariable String id) {
        return documentService.findById(id);
    }

    // 保存单个文档
    @PostMapping("/save")
    public MyDocument saveDocument(@RequestBody MyDocument document) {
        return documentService.save(document);
    }

    // 批量保存文档
    @PostMapping("/saveAll")
    public List<MyDocument> saveAllDocuments(@RequestBody List<MyDocument> documents) {
        return documentService.saveAll(documents);
    }

    // 删除文档
    @DeleteMapping("/{id}")
    public void deleteDocument(@PathVariable String id) {
        documentService.deleteById(id);
    }

    // 根据文本字段查询文档
    @GetMapping("/searchByText")
    public List<MyDocument> searchByTextField(@RequestParam String text) {
        return documentService.findByTextField(text);
    }

    // 根据文本和关键字字段查询文档
    @GetMapping("/searchByTextAndKeyword")
    public List<MyDocument> searchByTextAndKeyword(@RequestParam String text, @RequestParam String keyword) {
        return documentService.findByTextFieldAndKeywordField(text, keyword);
    }

    // 根据整数和布尔字段查询文档
    @GetMapping("/searchByIntegerAndBoolean")
    public List<MyDocument> searchByIntegerAndBoolean(@RequestParam Integer integerField, @RequestParam Boolean booleanField) {
        return documentService.findByIntegerFieldAndBooleanField(integerField, booleanField);
    }

    // 根据日期字段范围查询文档
    @GetMapping("/searchByDateRange")
    public List<MyDocument> searchByDateRange(@RequestParam String startDate, @RequestParam String endDate) {
        return documentService.findByDateFieldBetween(LocalDate.parse(startDate), LocalDate.parse(endDate));
    }

    // 高亮显示关键字查询文档
    @GetMapping("/searchWithHighlight")
    public List<MyDocument> searchWithHighlight(@RequestParam String keyword) {
        return documentService.searchWithHighlight(keyword);
    }

    // 获取 integerField 字段的聚合结果
    @GetMapping("/aggregate/integerField")
    public Map<Integer, Long> aggregateByIntegerField() {
        return documentService.aggregateByIntegerField();
    }
}
